package cn.qj.ymcc.service.impl;

import cn.qj.ymcc.api.SearchFeignAPI;
import cn.qj.ymcc.constants.BusinessConstants;
import cn.qj.ymcc.doc.CourseDoc;
import cn.qj.ymcc.domain.*;
import cn.qj.ymcc.dto.*;
import cn.qj.ymcc.mapper.CourseMapper;
import cn.qj.ymcc.service.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2025-07-24
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseTeacherService courseTeacherService;
    @Autowired
    private SearchFeignAPI searchFeignAPI;
    @Autowired
    private ICourseSummaryService courseSummaryService;

    @Override
    @Transactional
    public void save(CourseSaveDto courseSaveDto) {
        Course course = courseSaveDto.getCourse();
        CourseDetail courseDetail = courseSaveDto.getCourseDetail();
        CourseMarket courseMarket = courseSaveDto.getCourseMarket();
        CourseResource courseResource = courseSaveDto.getCourseResource();
        List<Long> teacharIds = courseSaveDto.getTeacharIds();
        //1.校验  非空校验
        //2.保存
        // course
        //查到老师的名字
        List<Teacher> teacherList = teacherService.selectBatchIds(teacharIds);
        String teacherNames = teacherList.stream().map(Teacher::getName).collect(Collectors.joining(","));
        course.setTeacherNames(teacherNames);
        //默认是下线
        course.setStatus(Course.STATUS_OFFLINE);
        insert(course);

        // courseDetail
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);

        // courseMarket
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);

        // courseResource
        courseResource.setCourseId(course.getId());
        courseResourceService.insert(courseResource);

        // courseTeacher
        ArrayList<CourseTeacher> courseTeachers = new ArrayList<>();
        teacharIds.forEach(tid -> {
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(tid);
            courseTeachers.add(courseTeacher);
        });
        courseTeacherService.insertBatch(courseTeachers);
    }

    /**
     * 课程上线
     *
     * @param courseId
     */
    @Override
    public void onlineCourse(List<Long> courseId) {
        //参数校验  TODO
        if(courseId == null || courseId.size() == 0){
            throw new RuntimeException("课程id不能为空");
        }
        //课程是否已上线 操作未上线的
        List<Course> courseList = selectBatchIds(courseId);
        if(courseList.size() != courseId.size()){
            throw new RuntimeException("课程不存在");
        }
        //判断是否已上线
        List<Course> onlineCourses = courseList.stream().filter(course -> Course.STATUS_ONLINE.equals(course.getStatus())).collect(Collectors.toList());
        if(onlineCourses.size() > 0){
            throw new RuntimeException("课程已上线");
        }
        //修改课程的状态
        courseList.forEach(course -> {
            course.setStatus(Course.STATUS_ONLINE);
            course.setOnlineTime(new Date());
        });
        updateBatchById(courseList);
        //======================================


        //准备一个list
        List<CourseDoc> courseDocs = new ArrayList<>();
        courseList.forEach(course -> {
            CourseDoc courseDoc = new CourseDoc();
            BeanUtils.copyProperties(course, courseDoc);


            //查询 t_course_market
            CourseMarket courseMarket = courseMarketService.selectById(course.getId());
            BeanUtils.copyProperties(courseMarket, courseDoc);

            //查询 t_course_summary
            CourseSummary courseSummary = courseSummaryService.selectById(course.getId());
            BeanUtils.copyProperties(courseSummary, courseDoc);

            courseDocs.add(courseDoc);
        });

        //调用搜索服务 给es同步数据
        searchFeignAPI.save(courseDocs);
        //为了不影响上面的运行效率 多线程 推送消息
        /*new Thread(() -> {
            publishMessage();
        }).start();*/
        publishMessage();

    }
    public void publishMessage(){
        //异步操作
        //1.发送消息 单项消息 同步消息 异步消息
        //2.消息的数据
        //3.消息推送 --打广告 短信推送 邮箱推送 站内推送

        //站内推送
        //发送数据
        MessageStationDto messageStationDto = new MessageStationDto();
        messageStationDto.setTitle("课程发布");
        messageStationDto.setContent("您的课程已上线，欢迎您的关注");
        messageStationDto.setType("course");
        //远程调用user服务 查询是否已读 类似search
        List<Long> userIds = Arrays.asList(1L, 2L, 3L, 4L);
        messageStationDto.setUserIds(userIds);
        SendResult sendResultStation = rocketMQTemplate.syncSend(BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TOPIC + ":"
                        + BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TAGS_STATION,
                MessageBuilder.withPayload(JSONObject.toJSONString(messageStationDto)).build());
        log.info("站内推送结果:{}",sendResultStation);

        //短信推送
        MessageSMSDto messageSMSDto = new MessageSMSDto();
        messageSMSDto.setTitle("课程发布");
        messageSMSDto.setContent("您的课程已上线，欢迎您的关注");
        List<UserPhoneDto> userPhoneDtos = Arrays.asList(
                new UserPhoneDto("127.0.0.1", 1L, "13800000000"),
                new UserPhoneDto("127.0.0.1", 2L, "13800000001"),
                new UserPhoneDto("127.0.0.1", 3L, "13800000002"),
                new UserPhoneDto("127.0.0.1", 4L, "13800000003")
        );
        messageSMSDto.setUserPhoneDto(userPhoneDtos);
        SendResult sendResultSMS = rocketMQTemplate.syncSend(BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TOPIC + ":"
                        + BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TAGS_SMS,
                MessageBuilder.withPayload(JSONObject.toJSONString(messageSMSDto)).build());
        log.info("短信推送结果:{}",sendResultSMS);


        //邮箱推送
        MessageEmailDto messageEmailDto = new MessageEmailDto();
        messageEmailDto.setTitle("课程发布");
        messageEmailDto.setContent("您的课程已上线，欢迎您的关注");
        messageEmailDto.setCopyto("123@qq.com");
        List<UserEmailDto> userEmailDtos = Arrays.asList(
                new UserEmailDto(1L, "123@qq.com"),
                new UserEmailDto(2L, "124@qq.com"),
                new UserEmailDto(3L, "125@qq.com"),
                new UserEmailDto(4L, "126@qq.com")
        );
        messageEmailDto.setUserEmailDtos(userEmailDtos);
        SendResult sendResultEmail = rocketMQTemplate.syncSend(BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TOPIC + ":"
                        + BusinessConstants.ROCKETMQ_COURSE_PUBLISH_TAGS_EMAIL,
                MessageBuilder.withPayload(JSONObject.toJSONString(messageEmailDto)).build());
        log.info("邮箱推送结果:{}",sendResultEmail);
    }
}
